package Java7_Concurrency_Cookbook.concurrent_custom.custom_executor_use_priority_blocking_queue;

import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <b>实现基于优先级的Executor类</b><br/>
 * <br/>
 * 执行器内部使用一个阻塞式队列存放等待执行的任务.<br/>
 * 此示例中使用PriorityBlockingQueue来存放待执行的任务, 待执行的任务需要实现Comparable接口<br/>
 * 哪个任务会被优先执行, 取决于任务的compareTo()方法实现<br/>
 * <br/>
 * 从执行结果来看, 执行器首先执行 Task0, Task1, 因为执行器会创建2个线程执行任务.<br/>
 * 其他线程按照优先级依次执行<br/>
 * @author lixiangke
 * @date 2017/11/24
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2,
                2,
                1,
                TimeUnit.SECONDS,
                /*new LinkedBlockingQueue<Runnable>()*/
                new PriorityBlockingQueue<Runnable>());
        for (int i = 0; i < 4; i++) {
            MyPriorityTask task = new MyPriorityTask("Zoom " + i, i);
            executor.execute(task);
        }
        TimeUnit.SECONDS.sleep(1);

        for (int i = 4; i < 8; i++) {
            MyPriorityTask task = new MyPriorityTask("Zoom " + i, i);
            executor.execute(task);
        }

        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.DAYS);
        System.out.printf("Main: End of the program.");
    }
}
